import 'dart:async';
import 'dart:convert';

import 'dart:math';

class FakeWebSocketServer {
  late StreamController<String> _controller;
  Timer? _marketTimer;
  Timer? _priceTimer;

  FakeWebSocketServer() {
    _controller = StreamController<String>.broadcast();
    //_startSendingData();
    _start();
  }

  Stream<String> get stream => _controller.stream;
  Random _random = Random();

  void _startSendingData() {
    _marketTimer = Timer.periodic(const Duration(seconds: 12), (timer) {
      var data = {
        "timestamp": DateTime.now().toIso8601String(),
        "market": [
          {"name": "美元指数", "price": (100 + _randomOffset()).toStringAsFixed(2)},
          {
            "name": "现货黄金",
            "price": (1900 + _randomOffset()).toStringAsFixed(2)
          },
          {
            "name": "欧元/美元",
            "price": (1.1 + _randomOffset(0.01)).toStringAsFixed(5)
          }
        ]
      };
      _controller.add(jsonEncode(data)); // 推送数据
    });
  }

  double _randomOffset([double max = 5]) =>
      (max * (1 - 2 * (DateTime.now().millisecondsSinceEpoch % 2)));

  void _start() {
    _priceTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
      List<String> codes = ["DXY", "USD"]; // 可变更的交易代码
      String randomCode = codes[_random.nextInt(codes.length)];
      double newPrice = _random.nextDouble() * 10 + 100; // 模拟价格变动

      var data = jsonEncode({"code": randomCode, "price": newPrice});
      _controller.add(data);
    });
  }

  void dispose() {
    _marketTimer?.cancel(); // ✅ 取消市场数据定时器
    _priceTimer?.cancel(); // ✅ 取消价格数据定时器
    _controller.close(); // ✅ 关闭 StreamController
  }
}

//final fakeServer = FakeWebSocketServer();
